package com.start.data.screen;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.ds.GroupDataSource;
import org.apache.commons.lang3.StringUtils;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.Map;

@Configuration
@MapperScan({"com.start.data.screen.mapper.**"})
@ComponentScan({"com.start.data.screen.**"})
@ConfigurationProperties(prefix = "start.data.screen")
public class StartDataScreenAutoConfiguration {
    @Autowired
    private DynamicRoutingDataSource dynamicRoutingDataSource;

    private String dataSource;


    public void setDataSource(String dataSource) {
        this.dataSource = dataSource;
    }

    public String getDataSource() {
        if (StringUtils.isEmpty(dataSource)) {
            return null;
        }
        Map<String, GroupDataSource> currentGroupDataSources = dynamicRoutingDataSource.getGroupDataSources();
        if (currentGroupDataSources.containsKey(dataSource)) {
            return dataSource;
        }
        Map<String, DataSource> currentDataSources = dynamicRoutingDataSource.getDataSources();
        if (currentDataSources.containsKey(dataSource)) {
            return dataSource;
        }
        throw new RuntimeException("数据源存在：" + dataSource);
    }
}
